<template>
    <div class="stepWrap" v-loading="loading">
        <el-steps :active="active" finish-status="success" process-status="process" align-center>
            <el-step title="评价规则" description="请设置评价计划基础信息"></el-step>
            <el-step title="评价范围" description="请上传评价人与被评人信息"></el-step>
            <el-step title="确认保存" description="请配置评价模板"></el-step>
        </el-steps>
        <div class="baseWidth" v-if="active==0">
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" id="ruleForm">
                <el-form-item label="评价计划名称" prop="plan_title" autocomplete="off">
                    <el-input v-model="ruleForm.plan_title" maxlength="20" @keyup.native="checkText($event,ruleForm.plan_title)"></el-input>
                </el-form-item>
                <el-form-item label="评价计划简介" prop="declaration">
                    <el-input type="textarea" v-model="ruleForm.declaration" maxlength="500" show-word-limit rows="3"></el-input>
                </el-form-item>
                <el-form-item label="评价计划图示" prop="img_url">
                    <el-upload :file-list="addImg" accept=".jpg, .png, .gif"  :before-upload="beforeAvatarUpload" :on-preview="handlePreview"  :on-change="handleChange" :on-remove="handleDel" action="" :http-request="upImg" list-type="picture-card" draggable :limit="9" :maxSize="30"
                            tip="最多上传9个文件,单个文件不要超过30M,请上传图像格式文件" :class="{imgHide:ruleForm.img_url.length==9}" >
                            <i slot="default" class="el-icon-plus"></i>
                        </el-upload>
                </el-form-item>
                <el-form-item label="发布时间" required style="">
                    <div style="width:320px;display: flex;justify-content:flex-start;align-items: center;margin-left: -10px;">
                        <el-col :span="11">
                        <el-form-item prop="date1">
                            <el-date-picker type="date" placeholder="选择日期" v-model="ruleForm.date1" :editable="false" value-format="yyyy-MM-dd"
                            format="yyyy-MM-dd"  style="width: 100%;"></el-date-picker>
                        </el-form-item>
                        </el-col>
                        <el-col class="line1" :span="2">-</el-col>
                        <el-col :span="11">
                        <el-form-item prop="date2">
                            <el-time-picker placeholder="选择时间" v-model="ruleForm.date2" format='HH:mm' :editable="false"  value-format='HH:mm' style="width: 100%;"></el-time-picker>
                        </el-form-item>
                        </el-col>
                    </div>
                </el-form-item>
                <el-form-item label="结束时间" required prop="finish">
                    <el-radio-group v-model="ruleForm.finish" active-color="#409EFF" inactive-color="#cccccc" active-value='1' inactive-value='0'>
                    <el-radio label="1">长期有效</el-radio>
                    <el-radio label="0">定时结束</el-radio>
                    </el-radio-group>
                    <div v-if="ruleForm.finish=='0'" style="width:320px;margin: 10px 0;display: flex;justify-content:flex-start;align-items: center;margin-left: -10px;">
                        <el-col :span="11">
                        <el-form-item prop="date3">
                            <el-date-picker type="date" placeholder="选择日期" v-model="ruleForm.date3" :editable="false" value-format="yyyy-MM-dd" format="yyyy-MM-dd" style="width: 100%;"></el-date-picker>
                        </el-form-item>
                        </el-col>
                        <el-col class="line1" :span="2">-</el-col>
                        <el-col :span="11">
                        <el-form-item prop="date4">
                            <el-time-picker placeholder="选择时间" v-model="ruleForm.date4" format='HH:mm' :editable="false" value-format='HH:mm' style="width: 100%;"></el-time-picker>
                        </el-form-item>
                        </el-col>
                    </div>
                </el-form-item>
                <el-form-item label="发布人推送显示" prop="message_send_name">
                    <div style="display: flex;align-items: center;">
                        <el-input v-model="ruleForm.message_send_name" maxlength="20" autocomplete="off"></el-input>
                        <el-tooltip class="item" effect="dark" content="横板推送消息，通知人信息" placement="right">
                            <i class="el-icon-question helpTip"></i>
                        </el-tooltip>
                    </div>
                </el-form-item>
                <el-form-item label="允许用户修改" prop="is_edit_eval">
                    <div style="display: flex;align-items: center;">
                        <el-switch v-model="ruleForm.is_edit_eval" active-color="#409EFF" inactive-color="#cccccc"  active-value='1' inactive-value='0'></el-switch>
                        <el-tooltip class="item" effect="dark" content="填写人是否可以修改已提交的评价信息" placement="right">
                            <i class="el-icon-question helpTip"></i>
                        </el-tooltip>
                    </div>
                </el-form-item>
                <el-form-item label="评价属性" prop="is_hidden">
                    <div style="display: flex;align-items: center;">
                        <el-radio-group v-model="ruleForm.is_hidden">
                            <el-radio label="0">实名评价</el-radio>
                            <el-radio label="1">匿名评价</el-radio>
                        </el-radio-group>
                        <el-tooltip class="item" effect="dark" content="实名可查看填写结果的人员信息，匿名则只可查看结果" placement="right">
                            <i class="el-icon-question helpTip"></i>
                        </el-tooltip>
                    </div>
                </el-form-item>
                <el-form-item label="可否自评" prop="is_self_eval">
                    <div style="display: flex;align-items: center;">
                        <el-radio-group v-model="ruleForm.is_self_eval" :disabled="ruleForm.plan_id!==''">
                            <el-radio label="1">可自评</el-radio>
                            <el-radio label="0">不可自评</el-radio>
                        </el-radio-group>
                        <el-tooltip class="item" effect="dark" content="当填写人与被评价人为同一人时，“不可自评”会将自己从被评价人列表中删除" placement="right">
                            <i class="el-icon-question helpTip"></i>
                        </el-tooltip>
                    </div>
                </el-form-item>
                <div style=" color: #f30;margin-top: -10px;margin-bottom: 20px;margin-left: 106px;"><i class="el-icon-info"></i>该项设置保存后不可二次编辑，请谨慎选择!</div>
                <el-form-item label="统计访问密码" prop="password" style="width: 360px;">
                    <div style="display: flex;align-items: center;">
                        <el-input v-model="ruleForm.password" maxlength="6" autocomplete="new-password" placeholder="请输入密码" show-password></el-input>
                    </div>
                </el-form-item>
                <div style=" color: #e89a24;margin-top: -10px;margin-bottom: 20px;margin-left: 106px;"><i class="el-icon-info"></i>密码最多可设置6位!</div>
                <el-form-item>
                    <el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
                    <el-button type="primary" :disabled='ruleForm.expand_data_status == -1' @click="next">下一步</el-button>
                    <!-- <el-button @click="resetForm('ruleForm')">重置</el-button> -->
                </el-form-item>
                </el-form>
                <el-dialog :visible.sync="dialogVisible">
                    <img width="100%" :src="dialogImageUrl" alt="">
                </el-dialog>
        </div>
        <div v-if="active==1" class="baseWidth">
                <el-form  :rules="rules" ref="downForm" label-width="" class="demo-ruleForm" v-loading="excelUploadloading">
                <el-form-item label="下载文件">
                    <el-select v-model="downType" placeholder="下载类型" style="margin-right: 5px;">
                        <el-option label="选择下载模板类型" value=""></el-option>
                        <el-option label="班级学生评价教师" value="1"></el-option>
                        <el-option label="学生评价教师" value="2"></el-option>
                        <el-option label="教师评价教师" value="3"></el-option>
                    </el-select>
                    <el-button :disabled="downType==''" @click="openExcelDialog">下载模板</el-button>
                    <span class="tip"><i class="el-icon-info"></i>请先选择下载文件类型</span>
                    <!-- downExcel -->
                </el-form-item>
                <el-form-item label="上传模板" style="align-items: stretch; width: 800px;">
                    <div v-if="ruleForm.status===1" style="display: flex;display: flex;align-items: center; margin-bottom: 10px;justify-content: flex-start;" id="upExcelWrap">
                        <el-select v-model="upParams.type" placeholder="上传类型" style="margin-right: 5px;">
                            <el-option label="选择上传模板类型" value=""></el-option>
                            <el-option label="班级学生评价教师" value="1"></el-option>
                            <el-option label="学生评价教师" value="2"></el-option>
                            <el-option label="教师评价教师" value="3"></el-option>
                        </el-select>
                        <el-upload
                        ref="myUpload"
                        class="excelUpload upload-disabled"
                        :action="upUrl"
                        :data="upParams"
                        :file-list="fileList"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :on-error="handleError"
                        :before-upload="beforeUpload"
                        accept='.xlsx,.xls'
                        :on-remove="handleRemove"
                        :limit="1"
                    >
                        <el-button :disabled="upParams.type==''"  type="primary">选择文件</el-button>
                        <span class="tip"><i class="el-icon-info"></i>请先选择上传文件类型</span>
                        </el-upload>
                    </div>
                <div slot="tip" class="el-upload__tip">只能上传excel文件。</div>
                    <!-- //@change="handleChange" -->
                    <el-collapse v-model="activeNames" style="width: 720px;" v-if="ruleForm.expand_data_status==2">
                        <el-collapse-item title="" name="1">
                            <template slot="title">
                            <i class="header-icon el-icon-s-grid"></i> 评价范围预览
                            </template>
                            <el-table  style="width: 100%" :data="tableData" border highlight-current-row stripe table-layout='auto'>
                                    <el-table-column
                                    v-for="(item,index) in tabledHead"
                                    :prop="item.key"
                                    :key="index"
                                    :label="item.title"
                                    align="center"
                                >
                                </el-table-column>
                             </el-table>
                            <el-pagination :currentPage=getExcelParams.pageNo :page-size=getExcelParams.pageSize :page-sizes="[10, 20,40, 50, 100]" :hide-on-single-page="getExcelParams.total==0"
                            layout="total, sizes, prev, pager, next, jumper" :total="getExcelParams.total" @size-change="handleSizeChange"
                            @current-change="handleCurrentChange" style="margin: 10px 0;">
                            </el-pagination>
                        </el-collapse-item>
                    </el-collapse>
                    <el-alert v-if="upError"
                        title="上传失败，详细如下："
                        type="error"
                        :description="upErrorMessage"
                        @close="upError=false"
                        >
                    </el-alert>
                    <el-empty v-if="!upError&&ruleForm.expand_data_status==0" description="未上传评价人与被评人模板"></el-empty>
                    <div v-if="!upError&&ruleForm.expand_data_status==1"><i class="el-icon-loading"></i> 未上传评价人与被评人模板导入中,请稍后...</div>
                </el-form-item>
                <el-form-item>
                    <el-button @click="prev()">上一步</el-button>
                    <!-- <el-button @click="prev()">隐藏预览数据</el-button> -->
                    <el-button type="primary" :disabled="ruleForm.expand_data_status!==2" @click="next()">下一步</el-button>
                    <el-button type="primary" size="medium" @click="back">到列表</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div v-if="active==2" class="baseWidth" :loading="step3Loading">
                <el-form  :rules="rules" ref="downForm" label-width="120px" class="demo-ruleForm">
                <!-- <el-form-item label="可否自评" prop="is_self_eval">
                    <el-radio-group v-model="ruleForm.is_self_eval">
                    <el-radio label="1">统一模版</el-radio>
                    <el-radio label="0">个性化模板</el-radio>
                    </el-radio-group>
                </el-form-item> -->
                <div style="padding: 0 0 20px 0;">
                    <h4>标签列表</h4>
                    <el-table
                    :data="lableData" border
                    style="width: 100%">
                    <el-table-column
                        prop="label_title"
                        label="标签">
                    </el-table-column>
                    <el-table-column
                        prop="model_title"
                        label="已选模版"
                       >
                       <template slot-scope="scope">
                            <el-link type="primary"   @click="handleChangeTep(scope.row)"  size="small" title="选择评价模版">
                               {{scope.row.model_id==''||scope.row.model_id==null?'请选择评价模版':scope.row.model_title}}
                            </el-link>
                        </template>
                    </el-table-column>
                    <el-table-column  fixed="right" label="操作" width="120" align="center">
                        <template slot-scope="scope">
                            <el-link type="primary" :disabled="scope.row.model_id==''||scope.row.model_id==null" @click="handleCopyAll(scope.row)"  size="small" title="发布应用到所有">应用到所有</el-link>
                        </template>
                        </el-table-column>
                    </el-table>
                </div>
                <el-form-item>
                    <el-button @click="prev()">上一步</el-button>
                    <el-button type="primary" @click="saveRelation()">确认保存</el-button>
                    <el-button type="primary" size="medium" @click="back">到列表</el-button>
                </el-form-item>
            </el-form>
            <el-dialog title="选择评价模版" :visible.sync="tepListDialog" width="640" height="640">
                <div style="height: 560px;overflow-y: auto;" v-loading="step3Loading">
                    <!-- prevent  @keyup.enter.native="tepList(1)"-->
                <el-form :inline="true" :model="temArgument" class="search" @keyup.enter.prevent="tepList(1)" style="height:auto; margin: 0 0 20px;overflow: hidden;
    height: 30px;">
                    <el-form-item>
                        <el-input v-model="temArgument.modelTitleKeyword" placeholder="搜索模版名称" clearable prefix-icon="el-icon-search"
                        @clear="tepList" style="width:150px;padding-left:5px"></el-input>
                    </el-form-item>
                </el-form>
                <el-table  style="width: 100%" :data="tepData" border align="center" highlight-current-row stripe table-layout='auto'>
                    <el-table-column
                    type="index"
                    width="50">
                    </el-table-column>
                    <el-table-column prop="model_title" label="评价模板标题"></el-table-column>
                    <el-table-column  fixed="right" label="操作" width="240" align="center">
                    <template slot-scope="scope">
                        <el-link  type="primary" @click="handleAdd(scope.row)"  size="small" :title="'选择【'+scope.row.model_title +'】'">选择</el-link>
                    </template>
                    </el-table-column>
                </el-table>
                   <!-- 分页 -->
                    <el-pagination :currentPage=temArgument.pageNo :page-size=temArgument.pageSize :page-sizes="[10, 20,40, 50, 100]" :hide-on-single-page="allTetal==0"
                    layout="total, sizes, prev, pager, next, jumper" :total="allTetal" @size-change="handleTepSizeChange"
                    @current-change="handleTepCurrentChange" style="padding-top: 0px;">
                    </el-pagination>
                </div>
            </el-dialog>
        </div>
        <div v-if="active==3" class="baseWidth">
            <el-result icon="success" title="创建成功" subTitle="评价计划创建完成，到列表进行发布！">
            <template slot="extra">
                <el-button type="primary" size="medium" @click="reseActive">重新编辑</el-button>
                <el-button type="primary" size="medium" @click="back">到列表</el-button>
            </template>
            </el-result>
        </div>
        <!-- <el-button style="margin-top: 12px;" @click="next">下一步</el-button>   default-expand-all-->
         <!-- 添加窗口 -->
        <el-dialog :title="downDialogTitle" :visible.sync="downDialogView" width="640">
            <div class="transferWrap" style="display: flex;margin-top: 10px;justify-content: space-between;">
                <div class="el-transfer-panel">
                    <div class="el-transfer-panel__header" style="display: flex;padding-right: 15px;justify-content: space-between; align-items: center;">
                        <div>可选择</div>
                        <el-checkbox v-model="checkAll" @change="handleCheckAllChange" style="font-size: 12px;display:flex;align-items: center;">全选</el-checkbox>
                        <!-- <el-link type="danger" title="清空已选择" @click="resetChecked">清空</el-link> -->
                    </div>
                    <div style="padding: 10px  20px  20px;;">
                    <el-input
                        placeholder="输入关键字进行过滤"
                        prefix-icon="el-icon-search"
                        clearable
                        v-model="filterText" style="margin: 10px 0;">
                    </el-input>
                    <div style="height: 360px;overflow-y: auto;">
                        <el-tree
                        :data="changingDialogData"
                        show-checkbox
                        node-key="id"
                        ref="tree"
                        accordion
                        highlight-current
                        :filter-node-method="filterNode"
                        @check="handleNodeClick"
                        :props="defaultProps">
                        </el-tree>
                    </div>
                </div>
                </div>
                <div class="el-transfer-panel">
                    <div class="el-transfer-panel__header" style="display: flex;padding-right: 15px;justify-content: space-between;">
                        <div>已选择({{changedObj.length}})</div>
                        <el-link type="danger" title="清空已选择" @click="resetChecked">清空</el-link>
                    </div>
                    <div style="margin: 20px;height:380px;overflow-y: auto; margin-right: 10px;padding-right: 10px;">
                        <div v-for="(item, index) in changedObj" :key="index" class="oneChangedStu" >
                            <div>{{item.label}}(<span class="remark">{{item.parent}}</span>)</div>
                            <el-link type="danger" title="移除" @click="remove(item.id)">移除</el-link>
                        </div>
                        <el-empty v-if="changedObj.length==0" description="未选择"></el-empty>
                    </div>
                </div>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="downDialogView = false">取 消</el-button>
                <el-button type="primary" :disabled="changedObj.length==0" @click="downFile">下载</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
// import { name } from 'file-loader';
// import SparkMD5 from 'spark-md5'
  export default {
    data() {
      return {
        active: 0,
        loading: false,
        plan_id: '',
        ruleForm: {
        'plan_id': '',
        'plan_title': '',
        'declaration': '',
        'img_url': [],
        'is_self_eval': '1',
        'is_edit_eval': '1',
        'is_hidden': '0',
        'date1': '',
        'date2': '',
        'date3': '',
        'date4': '',
        'message_send_name': '',
        'password': '',
        'begin_time': '',
        'expand_data_status': -1,
        'finish': '1',
        'end_time': '',
        'status': 1,
        },
        rules: {
            plan_title: [
            { required: true, message: '请输入评价计划名称', trigger: 'blur' },
            { min: 1, max: 30, message: '长度在 1 到 30 个字符', trigger: 'blur' }
          ],
          date1: [
            { required: true, message: '请选择发布日期', trigger: 'change' }
          ],
          date2: [
            { required: true, message: '请选择发布时间', trigger: 'change' }
          ],
          message_send_name: [
            { required: true, message: '请填写发布人推送显示', trigger: 'blur' }
          ] 
      },
        addImg: [],
        addedImg: {},
        // 预览已选择图片
        dialogImageUrl: '',
        // 预览图片窗口
        dialogVisible: false,
        fileList: [],
        // 下载模版标题
        downDialogTitle: '',
        downDialogView: false,
        excelUploadloading: false,
        // 下载-下载类型
        downType: '',
         // 下载-可选的学生
        students: [],
        // 下载-可选的教师
        teachers: [],
        // 下载-可选的班级
        classes: [],
        // 下载-当前操作的数据（以上3个之一）
        changingDialogData: [],
        // 下载--已选的发布对象(范围)
        changedObj: [],
         // 下载--可选范围搜索
        filterText: '',
        checkAll: false,
        // 树的配置
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        // excel上传地址
        upUrl: '',
        // excel 上传参数
        upParams: {
        'token': sessionStorage.token,
        'udid': sessionStorage.udid,
        'user_id': sessionStorage.user_id,
        'tech_id': sessionStorage.tech_id,
        'user_name': sessionStorage.use,
        'org_id': sessionStorage.org_id,
        'type': '',
        'plan_id': '',
        'version': 0
      },
        // 上传成功显示
         tabledHead: [],
         tableData: [],
         getExcelParams: {
            'plan_id': '',
            'grade_id': '',
            'class_id': '',
            'dept_id': '',
            'total': 0,
            'pageNo': 1,
            'pageSize': 10
         },
         activeNames: '',
         // 第三步标签数据
         step3Loading: false,
         lableData: [],
         // 模版列表
         tepListDialog: false,
         tepData: [],
         temArgument: {
            pageNo: 1,
            pageSize: 10,
            modelTitleKeyword: '',
            status: '1'
         },
         nowLabel: {},
         allTetal: 0,
         upError: false,
         upErrorMessage: '',
         show: false,
            value: ''
        }
    },
    mounted() {
        const _this = this
        this.loading = true
        const promise1 = new Promise((resolve, reject) => {
            this.getGrade(() => { resolve('1') })
        })
        const promise2 = new Promise((resolve, reject) => {
            this.getDepTeacher(() => { resolve('2') })
        })
        const allPro=[promise1, promise2]
        if (window.location.hash.split('?')[1]!==undefined) {
            this.plan_id = window.location.hash.split('?')[1].split('=')[1]
            this.upParams.plan_id=this.plan_id
            const promise3 = new Promise((resolve, reject) => {
                this.getPlanDetail(() => { resolve('3') })
            })
            allPro.push(promise3)
        }
        if (sessionStorage.IAS_plan_id!==undefined) {
            this.plan_id = sessionStorage.IAS_plan_id
            this.upParams.plan_id=sessionStorage.IAS_plan_id
            this.getPlanDetail(null)
        }
        Promise.all(allPro)
        .then((values) => { this.loading = false })
        .catch((error) => console.log(error))

        // excel上传接口
        this.upUrl = this.$api.add.upExcel.url
        if (sessionStorage.IASStep) {
            this.active= Number(sessionStorage.IASStep)
            if (this.active===2) {
                this.labelList()
            }
        }
        const hash=location.hash
         // 路由变化，执行数据加载，清空弹出层，时间框
         window.onhashchange = function (val) {
            if (hash !== location.hash) {
                console.log('跳')
                _this.$confirm('确定要离开本页面吗?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        closeOnHashChange: false,
                        lockScroll: true,
                        closeOnClickModal: false,
                        type: 'warning'
                    }).then(() => {
                        window.location.reload()
                    }).catch(() => {
                        window.location.hash = hash
                })
            }
        }
    },
    watch: {
      filterText(val) {
        this.$refs.tree.filter(val)
      },
      'ruleForm.finish': function(val) {
        // 处理逻辑
        if(val==1){
            this.ruleForm.date3=''
            this.ruleForm.date4=''
        }
     }
    },
    methods: {
        checkText (e,string) {
        const pattern = /[`~!@#$^\-&*()=|{}':;',\\\[\]\.<>\/?~！@#￥……&*（）——|{}【】'；：""'。，、？\s]/g
       // const pattern = /[`<>& /\\{}:| .，,|*=;%\s]/g
        const str = string.replace(pattern, '')
        this.ruleForm.plan_title = str
        },
        back() {
         window.location.href='#x41'
        },
        // 自适应表格列宽
      setWidth(str, tableData) {
        // str为该列的字段名(传字符串);tableData为该表格的数据源(传变量);
        str = str + ''
        let columnContent = ''
        let maxObj = null
        if (!tableData || !tableData.length || tableData.length === 0 || tableData === undefined) {
            return
        }
        if (!str || !str.length || str.length === 0 || str === undefined) {
            return
        }

        let nowL = str.replace('key', '')
            // 获取该列中最长的数据(内容)
            let index = 0
            for (let i = 0; i < tableData.length; i++) {
            if (tableData[i][nowL][str] === null) {
                return
            }

            const nowTemp = tableData[i][nowL][str].value || tableData[i][nowL][str].title + ''
            const maxTemp = (maxObj ? maxObj.value:'') || tableData[index][nowL][str].value || tableData[index][nowL][str].title + ''

            if (nowTemp.length > maxTemp.length) {
                // index = i
                maxObj = tableData[i][nowL][str]
            } else {
                maxObj = maxObj ||tableData[index][nowL][str] || tableData[index][nowL][str]
            }
            }
        console.log(maxObj.value)
        if (maxObj.type === 7) {
            for (let a = 0, b = maxObj.value.split(',').length; a < b; a++) {
            columnContent += '刘9'
            }
        } else {
            columnContent = maxObj.value || maxObj.title + ''
        }
        // 以下分配的单位长度可根据实际需求进行调整
        let flexWidth = 0
        for (const char of columnContent) {
            if ((char >= 'A' && char <= 'Z') || (char >= 'a' && char <= 'z')) {
            // 如果是英文字符，为字符分配8个单位宽度
            flexWidth += 12
            } else if (char >= '\u4e00' && char <= '\u9fa5') {
            // 如果是中文字符，为字符分配15个单位宽度
            flexWidth += 18
            } else {
            // 其他种类字符，为字符分配8个单位宽度
            flexWidth += 9
            }
        }
        if (flexWidth < 100) {
            // 设置最小宽度
            flexWidth = 100
        }
        return flexWidth + 'px'
        },
        // 树-过滤
        filterNode(value, data) {
            if (!value) return true
            return data.label.indexOf(value) !== -1
        },
        // 树-操作-单选
        handleNodeClick(data, all) {
            const setIds = this.changingDialogData.map(item => item.id)

            // if (setIds.some(item => all.checkedKeys.includes(item))) {
            if (setIds.every(item => all.checkedKeys.includes(item))) {
                console.log('arrayB包含于arrayA中')
                this.checkAll=true
            } else {
                console.log('arrayB不包含于arrayA中')
                this.checkAll=false
            }
            this.changedObj=[]
            this.$refs.tree.getCheckedNodes().map(item => {
                if (!item.children) {
                    this.changedObj.push(item)
                }
            })
        },
        // 树-操作-全选
        handleCheckAllChange() {
            const setIds=this.changingDialogData.map(item => item.id)
            this.$refs.tree.setCheckedKeys(this.checkAll?setIds:[])
           this.$nextTick(() => {
                this.changedObj=[]
                this.$refs.tree.getCheckedNodes().map(item => {
                    if (!item.children) {
                        this.changedObj.push(item)
                    }
                })
           })
        },
        // 树-操作-清空
        resetChecked() {
            this.checkAll=false
            this.$refs.tree.setCheckedKeys([])
            this.changedObj=[]
        },
        remove(id) {
            const filteredArray = this.changedObj.filter(item => item.id !== id)
            this.changedObj=filteredArray
            const setIds=this.changedObj.map(item => item.id)
            this.$refs.tree.setCheckedKeys(setIds)
        },
        // 下一步
        next() {
            if (this.active++ > 4) {
                this.active = 3
            } else {
                if (this.active===2) {
                    this.labelList()
                }
                if (this.active===1) {
                    this.ruleForm.img_url=this.addImg
                }
            }
            sessionStorage.IASStep=this.active
            console.log(this.active)
        },
        // 上一步
        prev() {
            if (this.active-- < 0) this.active = 0
            sessionStorage.IASStep=this.active
            console.log(this.active)
        },
        reseActive() {
            this.active = 0
            sessionStorage.IASStep=0
        },
       // Excel上传
        handleAvatarSuccess (res, fileList) {
             const _this=this
            _this.excelUploadloading=false
            this.$refs.myUpload.clearFiles()
            if (res.code === 200) {
                _this.ruleForm.expand_data_status=1
                _this.$alert('文件以上传成功，正在处理中', '提示', { type: 'success', closeOnHashChange: !1 })
                const checkTIme=setInterval(() => {
                    _this.checkFinish((status) => {
                        if (status===2) {
                            _this.$alert('文件处理完成，可点击[评价范围预览]查看详情', '提示', { type: 'success' })
                            clearInterval(checkTIme)
                        }
                    })
                }, 5000)
            } else {
                this.upError = true
                this.upErrorMessage = res.message
                _this.$alert('上传出错了，详见下表', '提示', { type: 'error', closeOnHashChange: !1 })
            }
            // fileList.url = res.url
            // this.hideUpload = true
            // this.fileList = []
            // this.fileList.push(fileList)
        },
        // 查询数据处理状态
        async checkFinish(okFun) {
            console.log('查询')
            const res = await this.$api.plan.detail.get({
                'plan_id': this.plan_id
            })
            if (res.code === 200) {
                // this.ruleForm=Object.assign(this.ruleForm, res.data)
                this.ruleForm.expand_data_status=res.data.expand_data_status
                if (this.ruleForm.expand_data_status === 2) {
                  this.previewList()
                }
                if (okFun)okFun(this.ruleForm.expand_data_status)
            } else {
                this.$alert(res.message, '提示', { type: 'error', closeOnHashChange: !1 })
            }
        },
        // 应用到所有
        handleCopyAll(model) {
          this.lableData.map(item => {
            item.model_id=model.model_id
            item.model_title=model.model_title
          })
        },
        handleRemove (file, fileList) {
            this.fileList = []
            this.hideUpload = false
        },
        handleError (err, file, fileList) {
            this.$alert(err, '提示', { type: 'error', closeOnHashChange: !1 })
        },
        upCheck (file) {
            if (this.upType === '') {
                this.$message.warning('请先选择上传的模版类型!')
                return false
            }
        },
        beforeUpload (file) {
            console.log(file)
            this.upError=false
            this.excelUploadloading=true
            // const isJPG = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            // if (!isJPG) {
            // this.$message.error('模版只支持 excel 格式!')
            // }
        },
        // 选择模版
        handleChangeTep(obj) {
          this.nowLabel=obj
          this.tepListDialog = true
          this.tepList()
        },
        // 下载模板或者Excel
        async downFile (type) {
            const parameter = {
                'org_id': sessionStorage.org_id,
                'token': sessionStorage.token,
                'udid': sessionStorage.udid,
                'plan_id': this.plan_id,
                'class_ids': '',
                'student_ids': '',
                'teacher_ids': '',
                'downloadProgress': '',
                'type': this.downType
            }
            const changeIds = this.changedObj.map(item => item.id).join(',')
            switch (Number(this.downType)) {
                case 1:
                parameter.class_ids = changeIds
                parameter.fileName = encodeURIComponent('班级学生评价教师模版.xlsx')
                    break
                case 2:
                parameter.student_ids = changeIds
                    parameter.fileName = encodeURIComponent('学生评价教师模版.xlsx')
                    break
                case 3:
                parameter.teacher_ids = changeIds
                    parameter.fileName = encodeURIComponent('教师评价教师模版.xlsx')
                    break
            }

        const downParameter = Object.assign(parameter, {})
        // 原始写法 新的是以流的方式下载，本地生成文件
         // window.location.href = (type === 1 ? this.$api.plan.downList.url : this.$api.plan.downImg.url) + '?' + this.parseParams(downParameter)
        // var url = type === 1 ? this.$api.planDetail.downTemplate.down(downParameter) : this.$api.planDetail.downExcel.down(downParameter)
        // const res = await url
        const _this=this
        const res = await this.$api.plan.downfile.get(downParameter, function() {
            _this.downDialogView=false
        })
        console.log(res)
        // if (res.code===200) {
        //   this.downDialogView=false
        // }
        },
        // 第一步提交
        async submitForm(formName) {
            let canSaveFlag = false
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    canSaveFlag = true
                }
            })
            if (!canSaveFlag) {
               return false
            }
            // 时间拼接
            this.ruleForm.begin_time=this.ruleForm.date1+' '+this.ruleForm.date2
            this.ruleForm.end_time =this.ruleForm.date3 ===''&& this.ruleForm.date4 ===''?'':this.ruleForm.date3+' '+this.ruleForm.date4
            if (Number(this.ruleForm.finish) === 0) {
                const { date3, date4 } = this.ruleForm
                if (!date3) {
                    this.$message.warning('请填写定时结束日期!')
                    return false
                }
                if (!date4) {
                    this.$message.warning('请填写定时结束时间!')
                    return false
                }
            }else{
                this.ruleForm.end_time=''
            }

            if (new Date(this.ruleForm.begin_time) > new Date(this.ruleForm.end_time) && this.ruleForm.end_time !=='') {
                this.$message.warning('定时结束时间不能早于发布时间!')
                return false
            }
            
            const saveData=JSON.parse(JSON.stringify(this.ruleForm))
            saveData.img_url=JSON.stringify(this.ruleForm.img_url)
            
            this.loading = true
            const res = await this.$api.plan.add.post(saveData)
            this.loading = false
            if (res.code === 200) {
                const isNewPlan = this.ruleForm.plan_id === '';
                if (isNewPlan) {
                    this.ruleForm.plan_id = res.data;
                    sessionStorage.IAS_plan_id = res.data;
                    this.plan_id = res.data;
                    this.upParams.plan_id = res.data;
                }
                if (isNewPlan) {
                 this.ruleForm.expand_data_status = 0;
                }
                const confirmMessage = isNewPlan ? '第一步创建完成，需要进行下一步吗?' : '编辑成功，需要进行下一步吗?';
                this.$confirm(confirmMessage, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    closeOnHashChange: false,
                    type: 'success'
                }).then(() => {
                    this.addImg=this.ruleForm.img_url
                    this.next();
                }).catch((error) => {
                    console.error('确认操作失败:', error);
                    // this.$alert('操作已取消', '提示', { type: 'info' });
                });
            } else {
                this.loading = false
                this.$alert(res.message, '提示', { type: 'error', closeOnHashChange: !1 })
            }
        },
        // 打开下载模版窗口
        openExcelDialog() {
            const _this=this
            _this.changedObj=[]
            _this.checkAll=false
            _this.$nextTick(() => {
                _this.$refs.tree.setCheckedKeys([])
            })
            if (_this.downType === '') {
                _this.$message.warning('请先选择要下载的模版类型!')
                return false
            }
            switch (Number(_this.downType)) {
                case 1:
                    _this.changingDialogData=_this.classes
                    _this.downDialogTitle='选择模版范围-[班级学生评价教师]'
                    break
                case 2:
                    _this.changingDialogData=_this.students
                    _this.downDialogTitle='选择模版范围-[学生评价教师]'
                    break
                case 3:
                _this.changingDialogData=_this.teachers
                    _this.downDialogTitle='选择模版范围-[教师评价教师]'
                    break
            }
            _this.downDialogView=true
        },
        handlePreview(file) {
            this.dialogImageUrl = file.url
            this.dialogVisible = true
        },
        beforeAvatarUpload(file, fileList) {
        //     let c = null
        //     const checkedImg = new Promise((resolve, reject) => {
        //         this.calculateMD5(file).then(value => {
        //         if (this.addedImg[value]===1) {
        //             this.$message.error('该文件已选择!')
        //             resolve(1)
        //         } else {
        //             // eslint-disable-next-line prefer-promise-reject-errors
        //             reject(1)
        //         }
        //         file.md5=value
        //     })
        //   })
        //   checkedImg.then(value => {
        //         if (this.addedImg[value]===1) {
        //             this.$message.error('该文件已选择!')
        //             return false
        //         }
        //         return c
        //     }).catch((err) => {
        //     // 失败回调处理
        //       console.log(err)
        //     })
        //   return checkedImg
        },
        handleChange(file, fileList) {
            this.ruleForm.img_url=fileList
        },
        handleDel(file, fileList) {
            this.ruleForm.img_url=fileList
        },
        imgChanged() {
            this.addedImg={}
            this.ruleForm.img_url.map(item => {
                this.addedImg[item.md5]=1
            })
            console.log(this.addedImg)
        },
        // 获取预览数据
        handleSizeChange (e) {
        this.getExcelParams.pageNo = 1
        this.getExcelParams.pageSize = e
        this.previewList()
        },
        // 分页操作-跳转到指定页 跳转到指定页数
        handleCurrentChange (e) {
            this.getExcelParams.pageNo = e
            this.previewList()
        },
        // 获取第三步 标签列表
        async labelList(okFun) {
             const res = await this.$api.plan.labelList.get({
                'plan_id': this.plan_id
            })
            if (res.code === 200) {
                this.lableData=res.data
            } else {
                this.$alert(res.message, '提示', { type: 'error', closeOnHashChange: !1 })
            }
        },
        handleTepCurrentChange (e) {
            this.temArgument.pageNo = e
            this.tepList()
        },
        handleTepSizeChange(e) {
            this.temArgument.pageNo = 1
            this.temArgument.pageSize = e
            this.tepList()
        },
        handleAdd(changedObj) {
            this.nowLabel.model_title=changedObj.model_title
            this.nowLabel.model_id=changedObj.id
            this.tepListDialog = false
            console.log(this.lableData)
        },
        // 获取模板列表
        async tepList (type) {
            if(type){
                this.temArgument.pageNo = 1
            }
            this.step3Loading = true
            const res = await this.$api.add.list.get(this.temArgument)
            if (res.code === 200) {
                this.tepData = res.data.data
                this.step3Loading = false
                // 分页
                this.allTetal = res.data.total
            } else {
                this.step3Loading = false
                this.$alert(res.message, '提示', { type: 'error', closeOnHashChange: !1 })
            }
        },
        // 第三步 保存标签和模版关系
        async saveRelation () {
            let saveJson=[]
            let emptyTip=[]
            this.lableData.map(item => {
                if (item.model_id ==='' || item.model_id === null) {
                    emptyTip.push(item.label_title)
                }
               const singgleObj={[item.label_id]: item.model_id}
               saveJson.push(singgleObj)
            })
            if (emptyTip.length>0) {
             this.$confirm('标签 ['+emptyTip.join(',')+'] 未选择评价模版', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        closeOnHashChange: !1,
                        type: 'warning'
                    })
                return false
            }
            this.loading = true
            const saveParameters={
                'plan_id': this.plan_id,
                'label_model_json': JSON.stringify(saveJson)
            }
            const res = await this.$api.plan.relation.post(saveParameters)
            if (res.code === 200) {
                this.loading = false
                this.next()
            } else {
                this.loading = false
                this.$alert(res.message, '提示', { type: 'error', closeOnHashChange: !1 })
            }
        },
        // 获取第二步 上传的excel列表
        async previewList(okFun) {
            this.getExcelParams.plan_id=this.plan_id
            const res = await this.$api.plan.previewList.get(this.getExcelParams)
            if (res.code === 200) {
                this.tabledHead = []
                // 生成表头
                res.data.head_list.map((item, index) => {
                    this.tabledHead.push({'key': 'key' + index, 'title': item})
                })
                let allDealData = []
                res.data.paging.data.map((item) => {
                    let dealData = {}
                    item.map((it, index) => {
                        dealData['key' + index] = it
                    })
                    allDealData.push(dealData)
                })
                this.tableData = allDealData
                this.loading = false
                // 分页
                this.getExcelParams.total = res.data.paging.total
            } else {
                this.$alert(res.message, '提示', { type: 'error', closeOnHashChange: !1 })
            }
        },
        // 获取第一步 计划详情（第二步上传后也调用）
        async getPlanDetail(okFun) {
            const res = await this.$api.plan.detail.get({
                'plan_id': this.plan_id
            })
            if (res.code === 200) {
                this.ruleForm=Object.assign(this.ruleForm, res.data)
                this.ruleForm.plan_id = this.ruleForm.id
                const startTime=this.ruleForm.begin_time.split(' ')
                this.ruleForm.finish=!!(this.ruleForm.end_time==null||this.ruleForm.end_time ==='')
                this.ruleForm.date1=startTime[0]
                this.ruleForm.date2=startTime[1]
                if (this.ruleForm.end_time == null||this.ruleForm.end_time ==='') {
                   this.ruleForm.end_time=''
                } else {
                    const endTime=this.ruleForm.end_time.split(' ')
                    this.ruleForm.date3=endTime[0]
                    this.ruleForm.date4=endTime[1]
                }
                debugger
                this.ruleForm.img_url=JSON.parse(this.ruleForm.img_url).map(item => { return {'name': item.name, 'url': item.url} })
                this.addImg=this.ruleForm.img_url
                console.log(this.ruleForm)
                this.ruleForm.is_self_eval= this.ruleForm.is_self_eval.toString()
                this.ruleForm.is_edit_eval=this.ruleForm.is_edit_eval.toString()
                this.ruleForm.is_hidden= this.ruleForm.is_hidden.toString()
                this.ruleForm.finish= this.ruleForm.end_time === null ||this.ruleForm.end_time ===''?'1':'0'
                this.ruleForm.status=res.data.status
                if (this.ruleForm.expand_data_status === 2) {
                  this.previewList()
                }
                if (okFun)okFun()
            } else {
                this.$alert(res.message, '提示', { type: 'error', closeOnHashChange: !1 })
            }
        },
        // 图片上传
        async upImg(file, fileList) {
            this.loading = true
            const res = await this.$api.base.imgUpload.post({
                'file': file.file
            })
            if (res.code === 200) {
                this.loading = false
                //   this.addImg.push({
                //     name: res.id,
                //     status:'success',
                //     url: res.url
                //  })
                this.ruleForm.img_url[this.ruleForm.img_url.length-1].url=res.url
                this.ruleForm.img_url[this.ruleForm.img_url.length-1].status='success'
            } else {
                this.loading = false
                this.$alert(res.message, '提示', { type: 'error', closeOnHashChange: !1 })
            }
        },
        // 获取所有年级班级及学生
        async getGrade(okFun) {
             const res = await this.$api.base.getAllGradeClassStudents.get({
                isAdmin: 1,
                supperAdmin: 1,
                from_src: 'fwh',
                returnStudent: 1
            })
            if (res.code === 200) {
                 this.students=[]
                 res.data.map((item, index) => {
                    const gradeObj = {
                        id: item.grade_number,
                        nid: item.grade_id,
                        label: item.grade_name,
                        children: []
                    }
                    this.classes.push({
                        id: item.grade_number,
                        nid: item.grade_id,
                        label: item.grade_name,
                        children: []
                    })
                    if (item.classes.length > 0) {
                        item.classes.map(it => {
                            const classObj = {
                                id: it.clas_id,
                                nid: it.clas_id,
                                label: it.clas_name,
                                parent: gradeObj.label
                            }
                            this.classes[index].children.push({
                                id: it.clas_id,
                                nid: it.clas_id,
                                label: it.clas_name,
                                parent: gradeObj.label
                            })
                            if (it.students && it.students.length > 0) {
                                classObj['children']=[]
                                it.students.map(ite => {
                                    const studentObj = {
                                        id: ite.stud_id,
                                        nid: ite.stud_id,
                                        label: ite.stud_name,
                                        parent: classObj.label
                                    }
                                    classObj.children.push(studentObj)
                                })
                                gradeObj.children.push(classObj)
                            }
                        })
                        this.students.push(gradeObj)
                    }
                })
               if (okFun)okFun()
            } else {
                this.$alert(res.message, '提示', { type: 'error', closeOnHashChange: !1 })
            }
        },
        // 获取所有部门及教师
        async getDepTeacher(okFun) {
             const res = await this.$api.base.getDepTeacher.get({})
            if (res.code === 200) {
                  res.data.map(item => {
                    const depObj = {
                        id: item.deptId,
                        label: item.deptName,
                        children: []
                    }
                    item.deptTechList.map(it => {
                        const teacherObj = {
                            id: it.tech_id,
                            label: it.tech_name,
                            parent:it.user_mobile
                        }
                        depObj.children.push(teacherObj)
                    })
                    this.teachers.push(depObj)
                })
                 if (okFun)okFun()
            } else {
                this.$alert(res.message, '提示', { type: 'error', closeOnHashChange: !1 })
            }
        }
    }

  }
</script>
<style>
.stepWrap {
    background-color: #fff;
    padding: 40px 20px 20px;

}
.line1 {text-align: center;}
.baseWidth { width: 800px;margin: 50px auto 20px auto;}

.el-upload--picture-card{
    width: 90px;
    height: 90px;
    border-radius: 0px;
    display: flex;
    align-items: center;
    justify-content: center;
}
.el-upload-list--picture-card .el-upload-list__item {
    width: 90px;
    height: 90px;
    border-radius: 0px;
}

.imgHide .el-upload--picture-card {
  display: none;
}

.excelUpload .el-upload-list {
    height: 20px;
}
.transferWrap .el-transfer-panel{
    width: 296px;
    /* max-height: 440px;
    overflow-y: scroll; */
}
.oneChangedStu {
    display: flex;
    align-items: center;
    justify-content: space-between;
    line-height: 30px;
} .oneChangedStu .remark {
        color: #aaa;
    }
.el-transfer-panel .el-transfer-panel__header .el-checkbox .el-checkbox__label  {
        font-size: 14px;
    }

.el-textarea .el-input__count {
    bottom: -34px;
    right: 0px;
    background: none;
}
.el-dialog__body {
    padding-top: 0;
}
.el-input__suffix {
  width: 40px;
}
.el-form-item {
    display: flex;
    align-items: center;
}
[class*=el-col-] {
    float: left;
}
.el-form-item__label {
    min-width: 100px;
}
#ruleForm .el-form-item__content {
    width: 480px;
    padding-left: 10px;
    max-width:none
}
#ruleForm.el-form .el-input__inner {
  max-width: 500px;
}
#ruleForm .el-textarea__inner {
    padding: 10px 15px;
}
#ruleForm .el-textarea {
    margin-left: 5px;
}

/* 添加一个自定义的类来指定上传组件在禁用时的样式 */
.upload-disabled .el-upload--disabled .el-upload-dragger {
  background-color: #f2f2f2; /* 更改颜色 */
  color: #909399; /* 更改文本颜色 */
  border-color: #e5e5e5; /* 更改边框颜色 */
  cursor: not-allowed; /* 更改鼠标指针样式 */
}
.tip {
    color: #99a9bf;
    padding-left: 10px
}
.el-scrollbar__wrap{
    overflow: auto;
    padding-bottom: 15px;
}
.helpTip {
    font-size: 24px;color: #c9d3df;margin-left:15px;
}
</style>
